package com.hl.manage.controller;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hl.manage.entity.Department;
import com.hl.manage.entity.Group;
import com.hl.manage.entity.Menu;
import com.hl.manage.service.IDepartmentService;
import com.hl.manage.service.IGroupService;
import com.hl.manage.service.IMenuService;
import com.hl.manage.utils.SendResult;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Helei
 * @since 2021-03-15
 */
@RestController
@RequestMapping("/manage/group")
public class GroupController {
	
	@Autowired
	IMenuService iMenuService;
	
	@Autowired
	IGroupService igservice;
	
	@Autowired
	IDepartmentService idpart;
	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deletebyid")
	public String delById(@RequestParam(name = "id") String id){
		SendResult sResult = new SendResult();
		if(igservice.removeById(id)) {
			sResult.setCode(200);
			sResult.setMsg("删除成功");
			sResult.setData(null);
			return sResult.toString();
		}else {
			sResult.setCode(400001);
			sResult.setMsg("操作失败，请重试");
			sResult.setData(null);
			return sResult.toString();
		}
	}
	/**
	 * 根据id修改或者新增
	 * @param param
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/updatebyid")
	public String updateById(@RequestParam(name = "param") String param) throws UnsupportedEncodingException {	
		JSONObject jObject = JSONObject.parseObject(URLDecoder.decode(param.replaceAll("%25", ""), "UTF-8"));
		SendResult sResult = new SendResult();
		Group goGroup ;
		if(jObject.get("id").toString().isEmpty()) {
			goGroup = new Group();
		}else {
			goGroup = igservice.getById(jObject.get("id").toString());
		}
		goGroup.setMenuIdlist(jObject.get("checked").toString().replace("[", "").replace("]", ""));
		goGroup.setName(jObject.get("name").toString());
		goGroup.setCompanyId(Integer.parseInt(jObject.get("company").toString()));
		if(igservice.saveOrUpdate(goGroup)) {
			sResult.setCode(200);
			sResult.setMsg("操作成功");
			sResult.setData(goGroup.toString());
			return sResult.toString();
		}else {
			sResult.setCode(400001);
			sResult.setMsg("操作失败，请重试");
			sResult.setData(goGroup.toString());
			return sResult.toString();
		}
	}
	/**
	 * 获取所有权限列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/getallmenu")
	public String getAllMenu(HttpServletRequest request) {	
		//顶级菜单存放数据
		List<Object> itemList = new ArrayList<Object>();
		List<Menu> melList =  iMenuService.findByParentId(0);
		for (Menu menu : melList) {
			//二级菜单存放数据
			List<Object> siList = new ArrayList<Object>();
			//处理上级菜单
			Map<String, Object> mapitem = new HashMap<String, Object>();
			mapitem.put("id", menu.getId());
			mapitem.put("label", menu.getName());
			JSONObject jsonObject = new JSONObject(mapitem);
			List<Menu> second =  iMenuService.findByParentId(menu.getId());
			for (Menu senMenu : second) {
				Map<String, Object> senmapitem = new HashMap<String, Object>();
				senmapitem.put("id", senMenu.getId());
				senmapitem.put("label", senMenu.getName());
				JSONObject sjObject = new JSONObject(senmapitem);
				//三级菜单处理
				List<Menu> threeList =  iMenuService.findByParentId(senMenu.getId());
				//三级菜单存放数据
				List<Object> thList = new ArrayList<Object>();
				for (Menu thMenu : threeList) {
					Map<String, Object> thitem = new HashMap<String, Object>();
					thitem.put("id", thMenu.getId());
					thitem.put("label", thMenu.getName());
					JSONObject thjObject = new JSONObject(thitem);
					thList.add(thjObject);
					
				}
				sjObject.put("children", thList);
				siList.add(sjObject);
			}
			jsonObject.put("children", siList);
			itemList.add(jsonObject);
		}
		SendResult sResult = new SendResult();
		sResult.setCode(200);
		sResult.setMsg("操作成功");
		sResult.setData(itemList.toString());
		return sResult.toString();
	}
	/**
	 * 分页获取所有权限列表
	 * @param page
	 * @param limit
	 * @param request
	 * @return
	 */
	@RequestMapping("/page")
	public String getAll(@RequestParam(name = "page")Integer page,@RequestParam(name = "limit") Integer limit,HttpServletRequest request) {
		HttpSession session = request.getSession();
		String comid = session.getAttribute("loginCompany").toString();
		List<Department> lidDepartments;
		Department department = null;
		
		IPage<Group> iPage = new Page<Group>(page, limit);
		List<Group> list = igservice.page(iPage).getRecords();
		List<String> list2 = new ArrayList<String>();
		//循环用户列表
		for (Group group : list) {
			JSONObject jObject = JSONObject.parseObject(group.toString());
			if (comid.equals("1")) {
				lidDepartments = idpart.findByPIT(0, 1, 1);
				jObject.put("company", lidDepartments);
			}else {
				lidDepartments = new ArrayList<Department>();
				department = idpart.getById(comid);
				lidDepartments.add(department);
				jObject.put("company", lidDepartments);
			}
			if((!session.getAttribute("loginGroup").equals(1))&&(!jObject.get("companyId").toString().equals(session.getAttribute("loginCompany").toString()))) {
				continue;
			}
			
			jObject.put("cName", idpart.getById(group.getCompanyId()).getName());
			
			//判断是否为超级管理员权限，如果是就不处理
			if(!jObject.get("menuIdlist").equals("-1")) {
				//把数据库逗号分隔的菜单id转换为string数组
				String[] strings = jObject.get("menuIdlist").toString().split(",");
				List<String> namList = new ArrayList<String>();
				List<Integer> lIntegers = new ArrayList<Integer>();
				//循环获取每一个id对应的名称
				for (String string : strings) {
					if(!string.isEmpty()) {
						lIntegers.add(Integer.parseInt(string));
						Menu menu = iMenuService.getById(Integer.parseInt(string));
						if(menu==null) {
							continue;
						}else {
							namList.add(menu.getName());
						}
					}
				}
				//获取权限列表
				//顶级菜单存放数据
				List<Object> itemList = new ArrayList<Object>();
				List<Menu> melList =  iMenuService.pageByParentId(0,0,9999999);
				for (Menu menu : melList) {
					//二级菜单存放数据
					List<Object> siList = new ArrayList<Object>();
					//处理上级菜单
					Map<String, Object> mapitem = new HashMap<String, Object>();
					mapitem.put("id", menu.getId());
					mapitem.put("label", menu.getName());
					JSONObject jsonObject = new JSONObject(mapitem);
					List<Menu> second =  iMenuService.pageByParentId(menu.getId(),0,9999999);
					for (Menu senMenu : second) {
						Map<String, Object> senmapitem = new HashMap<String, Object>();
						senmapitem.put("id", senMenu.getId());
						senmapitem.put("label", senMenu.getName());
						JSONObject sjObject = new JSONObject(senmapitem);
						//三级菜单处理
						List<Menu> threeList =  iMenuService.pageByParentId(senMenu.getId(),0,9999999);
						//三级菜单存放数据
						List<Object> thList = new ArrayList<Object>();
						for (Menu thMenu : threeList) {
							Map<String, Object> thitem = new HashMap<String, Object>();
							thitem.put("id", thMenu.getId());
							thitem.put("label", thMenu.getName());
							JSONObject thjObject = new JSONObject(thitem);
							thList.add(thjObject);
							
						}
						sjObject.put("children", thList);
						siList.add(sjObject);
					}
					jsonObject.put("children", siList);
					itemList.add(jsonObject);
				}
				
				jObject.put("select",lIntegers);
				jObject.put("menulist",itemList.toString());
				jObject.put("menuIdlist", namList.toString());
			}
			jObject.put("total", iPage.getTotal());
			list2.add(jObject.toJSONString());
		}
		SendResult sResult = new SendResult();
		sResult.setCode(200);
		sResult.setMsg("操作成功");
		sResult.setData(list2.toString());
		return sResult.toString();
	}
}
